/**
 * make 用户模型、登录、注册等业务逻辑
 */
const {
  Sequelize,
  Model,
  Op,
  DataTypes
} = require('sequelize')

const bcrypt = require('bcryptjs')

const {
  sequelize
} = require('../../../core/db')

const VaptchaSdk = require("../../services/vaptcha")

const exception = require('../../../core/exception')

const config = require('../../../config/config')

class User extends Model {
  static async verifyEmailPassword(ctx, email, password, code) {
    const user = await User.findOne({
      where: {
        email
      }
    })
    if (!user) {
      throw new exception.AuthFailed({ errMsg: '账号不存在' })
    }
    // user.password === password
    const correct = bcrypt.compareSync(password, user.password)
    console.log(correct)
    if (!correct) {
      throw new exception.AuthFailed({ errMsg: '密码不正确' })
    }
    
    // const vaptchaSdk = new VaptchaSdk(config.vaptcha.vid, config.vaptcha.key)
    // const val = await vaptchaSdk.validate(ctx.req, code, code)
    // console.log(val)
    // if (!val || !val.success || val.success != 1) {
    //   throw new exception.AuthFailed({ errMsg: '验证失败，请重试' })
    // }
    return user
  }
}

User.init({
  uid: DataTypes.BIGINT,
  email: DataTypes.STRING(128),
  password: {
    type: DataTypes.STRING,
    set(value) {
      const salt = bcrypt.genSaltSync(10)
      const psw = bcrypt.hashSync(value, salt)
      this.setDataValue('password', psw)
    }
  },
  nick_name: DataTypes.STRING,
  head_img: DataTypes.STRING(500),
  sex: {
    type: DataTypes.TINYINT,
    defaultValue: 0
  },
  post_job: DataTypes.STRING,
  address: DataTypes.STRING,
  introduction: DataTypes.STRING(100),
  status: {
    type: DataTypes.TINYINT,
    defaultValue: 1
  },
  grade: {
    type: DataTypes.TINYINT,
    defaultValue: 1
  },
  ip: DataTypes.STRING(20),
  user_type: DataTypes.TINYINT,
  last_at: DataTypes.DATE,
  remark: DataTypes.STRING(80),
  integral: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  mobile: DataTypes.STRING(11)
}, {
  sequelize,
  tableName: 'user',
  // 设置唯一索引
  indexes: [{
    unique: true,
    fields: ['uid', 'email']
  }]
})

module.exports = {
  User
}